package crons

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/consts"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/input/adminin"
	"hotgo/internal/service"
	"strings"
)

func init() {
	cron.Register(AddIntegral)
}

// AddIntegral 用户添加积分
var AddIntegral = &cAddIntegral{name: "add_integral"}

type cAddIntegral struct {
	name string
}

func (c *cAddIntegral) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cAddIntegral) Execute(ctx context.Context, parser *cron.Parser) (err error) {

	num := gconv.Float64(parser.Args[0])
	typeStr := "增加"
	if num < 0 {
		typeStr = "减少"
	}
	phones := garray.NewStrArrayFrom(strings.Split(gconv.String(parser.Args[1]), "\n")).
		FilterEmpty(). // 过滤空值
		Unique()       // 去重
	parser.Logger.Info(ctx, num, phones)
	errPhone := garray.NewStrArray()
	for _, phone := range phones.Slice() {
		user, err2 := service.AdminMember().GetByMobile(ctx, phone, consts.RoleAllUser)
		if err2 != nil || user == nil {
			if err2 != nil {
				parser.Logger.Error(ctx, err2.Error())
			}
			errPhone.Append(phone)
			continue
		}
		if _, err = service.AdminCreditsLog().SaveIntegral(ctx, &adminin.CreditsLogSaveIntegralInp{
			MemberId:    user.Id,
			AppId:       contexts.GetModule(ctx),
			CreditGroup: consts.CreditGroupOpIncr,
			Num:         num,
			Remark:      fmt.Sprintf("操作%s积分: %d", typeStr, gconv.Int(num)),
		}); err != nil {
			parser.Logger.Error(ctx, err.Error())
		}
		parser.Logger.Info(ctx, phone, fmt.Sprintf("操作%s积分: %d", typeStr, gconv.Int(num)))
	}
	if errPhone.Len() > 0 {
		parser.Logger.Warning(ctx, "操作失败手机号: ", errPhone.Join(","))
	}
	return
}
